const express = require('express')
const jwt1 = require('jwt-simple')
const crypto = require('crypto')

const jwt = {
    sign(value, secret) {
        return this.toBase64URL(crypto.createHmac('sha256', secret).update(value).digest('base64'))
    },
    toBase64URL(str) {
        return str.replace(/\=/g, '').replace(/\+/g, '-').replace(/\//, '_')
    },
    toBase64(content) {
        return this.toBase64URL(Buffer.from(JSON.stringify(content)).toString('base64'))
    },
    encode(payload, secret) {
        let v1 = this.toBase64({ typ: 'JWT', alg: 'HS256' }) // 表示这是jwt  基于sh256算法
        let v2 = this.toBase64(payload) // jwt 有效期 + 唯一标识
        let v3 = this.sign(v1 + '.' + v2, secret) // v1 + v2 加签名  生成jwt
        return [v1, v2, v3].join('.')
    },
    decode(token, secret) {
        let [v1, payload, sign] = token.split('.') // 用v1 v2 生成v3  判断与原来的是否相等
        let newSign = this.sign(v1 + '.' + payload, secret)
        if (newSign === sign) {
            let data = JSON.parse(Buffer.from(payload, 'base64url'))
            if (new Date().getTime() > data.expr) { // 有效期已过
                throw new Error('token 过期')
            }
            return data
        } else {
            throw new Error('token error')
        }
    }
}


const app = express()


app.get('/login', function (req, res) {
    let lastTime = new Date().getTime() + 1000 * 60 // 设置过期时间
    const token = jwt.encode({ name: 'ljp', expr: lastTime }, 'jwt')
    res.send({
        err: 0,
        data: {
            token
        }
    })
})


//http://localhost:3000/validate?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoibGpwIn0.tdUPEdMkmG7Tx--U6NQ3tBurYqrDUNuQnUeA_ipy9-I
app.get('/validate', function (req, res) {
    const token = req.query.token
    try {
        let data = jwt.decode(token, 'jwt')
        res.send({
            err: 0,
            data
        })
    } catch (error) {
        console.log(error)
        res.send({
            err: error
        })
    }

})



app.listen(3000, () => {
    console.log('server start port=3000')
})